<template>
	<view class="content">
		<!-- 公共组件 -->
		<public-module></public-module>

		<!-- 权限控制视图 -->
		<view v-if="isUser">
			<!-- 轮播图 -->
			<swiper
				class="banner-box"
				indicator-color="rgba(255, 255, 255, 0.3)"
				indicator-active-color="#FFFFFF"
				:indicator-dots="true"
				:autoplay="true"
				:interval="3000"
				:duration="500"
			>
				<swiper-item v-for="(item, index) in bannerList" :key="index">
					<image :src="item" mode="aspectFill" lazy-load></image>
				</swiper-item>
			</swiper>

			<!-- 项目详情卡片 -->
			<view class="project-container pd16_15" v-if="projects.length > 0">
				<!-- 价格卡片 -->
				<view class="price-card">
					<view class="project-name">{{ currentProject.name }}</view>
					<view 
						class="price-options"
						:class="{
							'four-items': periodCount === 4,
							'more-items': periodCount > 4
						}"
					>
						<view 
							v-for="(price, key) in periodPricing" 
							:key="key" 
							class="option-item"
							:class="{ 'active': selectedPeriod === key, 'has-tag': key === 'year' }"
							@click="selectPeriod(key)"
						>
							<!-- 活动角标 - 只在年选项显示 -->
							<view class="activity-tag" v-if="key === 'year'">活动</view>
							
							<view class="period">{{ getPeriodName(key) }}</view>
							<view 
								class="market-price" 
								v-if="marketPriceDuration[key] && marketPriceDuration[key] !== price"
							>
								市场价: {{ marketPriceDuration[key] / 100 }}元
							</view>
							<view v-if="marketPriceDuration[key] && marketPriceDuration[key] !== price" class="current-price">{{ price / 100 }}元</view>
							<view v-else class="current-price"  style="margin-top: 12px;">{{ price / 100 }}元</view>
						</view>
					</view>
					<u-button 
						class="reserve-btn" 
						shape="circle"
						@click="handleReserve(currentProject.id)"
						:custom-style="{
							background: tempColor,
							fontSize: '32rpx',
							color: '#fff'
						}"
					>
						立即预约
					</u-button>
				</view>

				<!-- 服务说明卡片 -->
				<view class="info-card">
					<view class="title">服务说明</view>
					<view class="info-content">{{ currentProject.info }}</view>
				</view>
			</view>
		</view>

		<!-- 非用户权限视图（可选） -->
		<view v-else class="permission-tip">工作人员页面暂未开发</view>

		<!-- 底部导航 -->
		<f-tabbar></f-tabbar>
	</view>
</template>

<script>
import { mapState } from 'vuex';
import fTabbar from '@/components/module/f-tabbar/f-tabbar';
import theme from '@/common/theme';
import { isLogin } from '@/plugins/auth';
import { getProjectTypeList, getProjectList } from '@/apis/index_callback.js';
import store from '@/store';

export default {
	components: {
		fTabbar
	},
	data() {
		return {
			isUser: true,
			loading: false,
			isWork: false,
			isAdmin: false,
			userInfo: uni.getStorageSync('userInfo'),
			selectIndex: 0,
			projects: [],
			tempColor: theme.btnDefaultBg,
			fontSizeLg: uni.rpx2px(theme.fontSizeLg) + 'px',
			currentProject: {}, // 当前展示的项目
			periodPricing: {}, // 当前价格
			periodName: {}, // 服务名称
			marketPriceDuration: {}, // 市场价
			selectedPeriod: 'year', // 默认选中的周期
			bannerList: []
		};
	},
	onLoad() {
		uni.hideTabBar();
		this.checkPermission();
	},
	
	onShow(){
		if(this.userInfo){
			this.checkPermission();
		}
	},
	computed: {
		// 计算价格选项数量
		periodCount() {
			return Object.keys(this.periodPricing).length;
		}
	},
	watch: {
		// 当项目数据加载完成后，设置当前项目
		projects: {
			handler(newVal) {
				if (newVal.length > 0) {
					this.currentProject = newVal[0];
					this.parsePriceData();
				}
			},
			immediate: true
		}
	},
	methods: {
		// 权限校验
		async checkPermission() {
			if (isLogin()) {
				let roles = this.userInfo.roles;
				if (roles && roles.length > 0) {
					switch (roles[0].role_key) {
						case 'user':
							this.isUser = true;
							this.getHomeData();
							break;
						case 'admin':
							this.isUser = false;
							this.isAdmin = true;
							break;
						case 'work':
							this.isUser = false;
							this.isWork = true;
							break;
						default:
							this.isUser = true;
							this.getHomeData();
					}
					return;
				}
				this.isUser = true;
				this.getHomeData();
			} else {
				this.getHomeData();
			}
		},
		
		// 解析价格数据
		parsePriceData() {
			if (this.currentProject.period_pricing) {
				try {
					this.periodPricing = JSON.parse(this.currentProject.period_pricing);
				} catch (e) {
					console.error('解析价格数据失败:', e);
					this.periodPricing = {};
				}
			}
			
			if (this.currentProject.market_price_duration) {
				try {
					this.marketPriceDuration = JSON.parse(this.currentProject.market_price_duration);
				} catch (e) {
					console.error('解析市场价格数据失败:', e);
					this.marketPriceDuration = {};
				}
			}

			if (this.currentProject.period_name) {
				try {
					this.periodName = JSON.parse(this.currentProject.period_name);
				} catch (e) {
					console.error('解析服务类型名称失败:', e);
					this.periodName = {};
				}
			}
		},
		
		// 获取周期名称
		getPeriodName(key) {
			return this.periodName[key]
		},
		
		// 选择价格周期
		selectPeriod(period) {
			this.selectedPeriod = period;
		},
		
		// 处理预约
		handleReserve(projectId) {
			if (!this.selectedPeriod) {
				uni.showToast({
					title: '请选择服务周期',
					icon: 'none'
				});
				return;
			}
			if (!isLogin()) {
				// 未登录，调用登录接口
				this.judgeLogin();
			}else{
				store.commit('setLoadingShow', true);
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages2/order/create?id=' + projectId+"&period="+this.selectedPeriod
					});
				}, 500)
			
			}			
		},
		
		// 获取首页数据
		async getHomeData() {
			store.commit('setLoadingShow', true);
			getProjectList(
				{ status: 1 },
				(res) => {
					store.commit('setLoadingShow', false);
					
					this.projects = res;
					this.bannerList = JSON.parse(res[0].rotation);
				},
				(err) => {
					console.error('获取项目列表失败:', err);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				}
			);
		}
	}
};
</script>

<style lang="scss" scoped>
@import '@/common/variables.scss';

.banner-box {
	height: 440rpx;
	position: relative;

	image {
		width: 100%;
		height: 440rpx;
		border-radius: 0 0 30rpx 30rpx;
	}
}

.project-container {
	position: relative;
	margin-top: -40rpx;
	background: $bg-color;
	border-radius: 32rpx 32rpx 0rpx 0rpx;
}

.price-card {
	background: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	margin-bottom: 30rpx;
	position: relative;
}

.project-name {
	font-size: $font-size-lg;
	font-weight: bold;
	color: $text-color;
	margin-bottom: 30rpx;
	text-align: center;
}

.price-options {
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
	margin-bottom: 30rpx;
	
	// 默认布局 - 每行3个
	&:not(.four-items):not(.more-items) {
		.option-item {
			width: 32%;
		}
	}
	
	// 4个选项时的布局 - 每行2个
	&.four-items {
		.option-item {
			width: 48%;
			margin-bottom: 30rpx;
		}
	}
	
	// 超过4个选项时的布局 - 每行3个
	&.more-items {
		.option-item {
			width: 32%;
		}
	}
}

.option-item {
	background: #f8f9fa;
	border-radius: 12rpx;
	padding: 20rpx 0;
	margin-bottom: 20rpx;
	text-align: center;
	border: 2rpx solid transparent;
	transition: all 0.3s;
	box-sizing: border-box;
	position: relative;
	
	.period {
		font-size: $font-size-base;
		color: $text-color;
		font-weight: bold;
		margin-bottom: 10rpx;
	}
	
	.market-price {
		font-size: $font-size-sm;
		color: $text-color-notice;
		text-decoration: line-through;
		margin-bottom: 10rpx;
	}
	
	.current-price {
		font-size: $font-size-base;
		color: $cl-price;
		font-weight: bold;
	}
	
	// 选中状态样式
	&.active {
		border-color: $btn-primary-bg;
		background-color: rgba($btn-primary-bg, 0.05);
		box-shadow: 0 0 10rpx rgba($btn-primary-bg, 0.2);
		
		.current-price {
			font-size: $font-size-lg;
			color: darken($cl-price, 10%);
		}
	}
	
	// 活动角标样式
	.activity-tag {
		position: absolute;
		top: -10rpx;
		right: -10rpx;
		background-color: #ff3333;
		color: white;
		font-size: 20rpx;
		padding: 4rpx 12rpx;
		border-radius: 20rpx;
		z-index: 10;
		box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.2);
		transform: rotate(10deg);
		font-weight: bold;
	}
}

.reserve-btn {
	height: 80rpx;
	line-height: 80rpx;
	border-radius: 40rpx;
	color: #fff;
	text-align: center;
	font-size: $font-size-lg;
	font-weight: bold;
	margin-top: 20rpx;
	background: $btn-primary-bg;
}

.info-card {
	background: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.title {
	font-size: $font-size-lg;
	font-weight: bold;
	color: $text-color;
	margin-bottom: 20rpx;
	padding-bottom: 15rpx;
	border-bottom: 1rpx solid $border-color;
}

.info-content {
	font-size: $font-size-base;
	color: $text-color;
	line-height: 1.6;
}

/* 保留原有必要样式 */
.permission-tip {
	margin-top: 200rpx;
	text-align: center;
	font-size: $font-size-base;
	color: $text-color-notice;
}

.pd16_15 {
	padding: 32rpx 30rpx;
}
</style>